import * as NSBase from '../NetServiceBase';
import { Guid } from '../../TYLibrary/System/System';
import { IShareManager } from '../IManager';
import { IsNull, Random } from '../../TYLibrary/Common/GlobalExtend';
import { ManagerBase } from './ManagerBase';
import { T_ShareInfo, Logger, LogLevel } from '../EntityBase';

//T_ShareInfo
//NSBase.GetShareInfo
//NSBase.AddTRecommend

export class ShareManager extends ManagerBase implements IShareManager {
	public GetShareInfoUrl: string = "";
	public AddTRecommendUrl: string = "";

	public async Init() {
		let r = await NSBase.GetShareInfo(this.GetShareInfoUrl);
		if (!IsNull(r)) {
			wx.setStorageSync('ShareInfo', r);
		}
	}

	public onShareAppMessage(options?: { from: string, target: any }): { title?: string, path?: string, imageUrl?: string } {
		let r = wx.getStorageSync('ShareInfo') as Array<T_ShareInfo>;
		let s = r[Random(0, r.length)];
		let guid = Guid.NewGuid().replace(/-/g, '');
		if (this.m_App.WXLoginInfo && this.m_App.WXLoginInfo.UnionID) {
			s.PATH = s.PATH.replace('{{ReferralCode}}', guid);
			NSBase.AddTRecommend(this.AddTRecommendUrl, guid, this.m_App.WXLoginInfo.UnionID).then((res) => {
				Logger.Debug(LogLevel.L1, res);
			});
		} else
			s.PATH = s.PATH.replace('?ReferralCode={{ReferralCode}}', '');

		let Isbutton = false;
		if (options.from == 'button')
			Isbutton = true;
		if (s.PATH.indexOf('?') > 0)
			s.PATH = s.PATH + '&Isbutton=' + Isbutton;
		else
			s.PATH = s.PATH + '?Isbutton=' + Isbutton;

		Logger.Debug(LogLevel.L1, options, s);
		return {
			title: s.TITLE,
			path: s.PATH,
			imageUrl: s.IMAGEURL
		};
	}
}
